package afcp.alumni.action.event;

import java.util.List;

import net.sourceforge.stripes.action.Message;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.security.Secure;
import net.sourceforge.stripes.validation.Validate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import afcp.alumni.action.base.EventAction;
import afcp.alumni.action.page.AdminAction;
import afcp.alumni.model.db.Member;
import afcp.alumni.service.impl.MemberServiceImpl;

@UrlBinding(ManageMemberAction.URL)
@Secure(roles = Member.ROLE_ADMIN)
public class ManageMemberAction extends EventAction {

	@Override
	protected String fromUrl() {
		return AdminAction.URL;
	}

	@Override
	public String getUrl() {
		return URL;
	}

	@Override
	public Resolution view() {
		return fromRedirect();
	}

	public static final String URL = "/memberaction";
	
	private static final Log logger = LogFactory.getLog(ManageMemberAction.class);

	@SpringBean
	private MemberServiceImpl memberService;
	
	


	
	
	// Generate password form
	
	private String idPasswordMember;

	public String getIdPasswordMember() {
		return idPasswordMember;
	}

	public void setIdPasswordMember(String idPasswordMember) {
		this.idPasswordMember = idPasswordMember;
	}
	
	public Resolution generatePassword() {
		// TODO déterminer autrement la langue des mails de mot de passe envoyés.
		List<Message> messages = memberService.generatePassword(idPasswordMember, context.getLocale());
		if (messages != null) {
			for (Message message : messages) {
				addFlashScope(PROBLEM_FLASHSCOPE_KEY, message);
			}
		}
		
		return fromRedirect();
	}
	
	public Resolution generateAllPasswords() {
		List<Message> messages = memberService.generateAllPasswords(context.getLocale());
		if (messages != null) {
			for (Message message : messages) {
				addFlashScope(PROBLEM_FLASHSCOPE_KEY, message);
			}
		}
		
		return fromRedirect();
	}
	
	// End generated password

	
	// Delete member form

	private Member deletedMember;

	/**
	 * Getter to display in the JSP which member has just been deleted.
	 * 
	 * @return The {@link Member} object of the deleted Member
	 */
	public Member getDeletedMember() {
		return deletedMember;
	}

	// TODO non géré par les redirections en cas d'erreur. à reporter dans une
	// validation method qui écrit un message ajouté au flash scope
	@Validate(required = true, on = "removeMember")
	private String idDeletedMember;

	public void setIdDeletedMember(String idDeletedMember) {
		this.idDeletedMember = idDeletedMember;
	}

	public static final String DELETEMEMBER_MSG_KEY = "deletemember";

	/**
	 * Method called by the member deletion form. Remove a member from the
	 * datastore by calling the service method
	 * {@link MemberServiceImpl#removeMemberFromKeyString(String)}.
	 * 
	 * @return
	 */
	public Resolution removeMember() {
		// delegate to the service. Since the member already exists, the bean
		// will be made by the DAO.
		deletedMember = memberService.removeMember(idDeletedMember);
//		logger.info("Membre supprimé. Identifiant : "
//				+ idDeletedMember
//				+ (deletedMember == null ? "" : ", prénom : "
//						+ deletedMember.getFirstName() + ", nom : "
//						+ deletedMember.getLastName()));
		Message memberDeleted;
		if (deletedMember == null) {
			memberDeleted = msgObj("message.deletemember", idDeletedMember);
		} else {
			memberDeleted = msgObj("message.deletemember.withname", idDeletedMember, deletedMember.getFirstName(), deletedMember.getLastName());
		}
		logger.info(msgToStr(memberDeleted));
		addFlashScope(DELETEMEMBER_MSG_KEY, memberDeleted);

		return fromRedirect();
	}

	// End delete member form
	
	
	
	// Delete all members form
	
	public Resolution removeAllMembers() {
		Message allMemberDeleted;
		if (memberService.removeAllMembers(context)) {
			allMemberDeleted = msgObj("message.deleteallmembers.success");
		} else {
			allMemberDeleted = msgObj("message.deleteallmembers.fail");
		}
		logger.info(msgToStr(allMemberDeleted));
		addFlashScope(DELETEMEMBER_MSG_KEY, allMemberDeleted);

		return fromRedirect();
	}
	
	// End delete all members

	

	// Formulaire d'ajout de rôles

	// TODO non géré par les redirections en cas d'erreur. à reporter dans une
	// validation method qui écrit un message ajouté au flash scope
//	@ValidateNestedProperties({
//			@Validate(field = "id", required = true, on = "addRole"),
//			@Validate(field = "label", required = true, on = "addRole") })
//	private Role newRole;
//
//	public Role getNewRole() {
//		return newRole;
//	}
//
//	public void setNewRole(Role newRole) {
//		this.newRole = newRole;
//	}
//
//	// TODO utiliser les messages dans flashscope à la place
//	@ValidationMethod(on = "addRole")
//	public void validateRole(ValidationErrors errors) {
//		if (memberService.roleExists(newRole)) {
//			errors.addGlobalError(new LocalizableError("database.alreadyexists"));
//			newRole = null; // Pour ne pas afficher sur la JSP qu'il a été créé
//		}
//	}
//
//	public static final String NEWROLE_MSG_KEY = "newrole";
//
//	public Resolution addRole() {
//		memberService.addOrUpdateRole(newRole);
//		addFlashScope(NEWROLE_MSG_KEY, msgObj("message.newrole", newRole.getLabel()));
//		return fromRedirect();
//	}
//
//	// End formulaire d'ajout de rôles
//	
//
//	// delete role button
//
//	private Role deletedRole;
//
//	/**
//	 * Getter to display in the JSP which member has just been deleted.
//	 * 
//	 * @return The {@link Member} object of the deleted Member
//	 */
//	public Role getDeletedRole() {
//		return deletedRole;
//	}
//
//	// TODO non géré par les redirections en cas d'erreur. à reporter dans une
//	// validation method qui écrit un message ajouté au flash scope
//	@Validate(required = true, on = "removeRole")
//	private String idDeletedRole;
//
//	public void setIdDeletedRole(String idDeletedRole) {
//		this.idDeletedRole = idDeletedRole;
//	}
//
//	public static final String DELETEROLE_MSG_KEY = "deleterole";
//
//	/**
//	 * Method called by the role deletion form. Removes a role from the
//	 * datastore by calling the service method
//	 * {@link MemberServiceImpl#removeRole(String)}.
//	 * 
//	 * @return
//	 */
//	public Resolution removeRole() {
//		// delegate to the service. Since the member already exists, the bean
//		// will be made by the DAO.
//		deletedRole = memberService.removeRole(idDeletedRole);
//		logger.info("Rôle supprimé. Identifiant : "
//				+ idDeletedRole
//				+ (deletedRole == null ? "" : ", id : " + deletedRole.getId()
//						+ ", libellé : " + deletedRole.getLabel()));
//		Message roleDeleted;
//		if (deletedMember == null) {
//			roleDeleted = msgObj("message.deleterole", idDeletedRole);
//		} else {
//			roleDeleted = msgObj("message.deleterole.withlabel", idDeletedRole, deletedRole.getLabel());
//		}
//		addFlashScope(DELETEROLE_MSG_KEY, roleDeleted);
//
//		return fromRedirect();
//	}

	// end delete role button
	
	
	
	

}
